////// EzMemberSelector
(function ($, undefined) {

    // define the name of the UI component
    var ui_name = "memberSelector"

    // initialize object
    var ms = $.memberSelector = {

        // default values
        defaults: {
            deptList: [],
            memberChanged: function () { }
        },

        setDefaults: function (defaultOptions) {
            this.defaults = $.extend({}, this.defaults, defaultOptions);
        }

    };

    $.fn.memberSelector = function (options) {

        var _cmbDeptList = null;
        var _cmbMemberList = null;
        var _selectUserId = null;
        var _domInitialized = false;


        // method calling
        if (typeof options == 'string') {
            var args = Array.prototype.slice.call(arguments, 1),
			    res;
            this.each(function () {
                var data = $.data(this, ui_name);
                if (data) {
                    var meth = data[options];
                    if (meth) {
                        var r = meth.apply(this, args);
                        if (res === undefined) {
                            res = r;
                        }
                    }
                }
            });
            if (res !== undefined) {
                return res;
            }
            return this;
        }

        // initialize options
        options = $.extend({}, ms.defaults, options);

        this.each(function () {
            var _self = this;

            if (_self) {
                var dom = getInitializeDom(options);
                $(this).append(dom);
            }

            // initialize callback
            for (var key in options) {
                var value = options[key];
                if (typeof value == 'function') {
                    // bind callbacks
                    $(_self).bind(key, value);
                }
            }

            /* Private Methods
            -----------------------------------------------------------------------------*/
            function _accessor() {

                var accessor = {};

                if (ezmock.IS_MOCKED) {
                    var mock_memberList = [
                       {
                           'Id': '11111',
                           'Name': '李6'
                       },
                       {
                           'Id': '22222',
                           'Name': '李7'
                       },
                       {
                           'Id': '33333',
                           'Name': '李8'
                       }
                     ];

                    var mock_deptList = [
                        {
                            'Id': '111',
                            'DeptName': '软件工程'
                        },
                        {
                            'Id': '222',
                            'DeptName': '策划'
                        },
                        {
                            'Id': '333',
                            'DeptName': '设计'
                        }
                    ];

                    var mockAccessor = {
                        'getDeptList': function () {
                            return mock_deptList;
                        },

                        'doUpdateMemberList': function () {
                            _bindMemberList(mock_memberList);

                        }
                    }
                    accessor = mockAccessor;
                }
                else {
                    var realAccessor = {
                        'getDeptList': function () {
                            return options.deptList;
                        }
                    }
                    accessor = realAccessor;
                }
                return accessor;
            };

            //将Json格式的部门列表转换成数组
            function _getDeptListForArray(deptList) {
                var deptListForArray = [];
                for (var key in deptList) {
                    var name = deptList[key].DeptName;
                    var id = deptList[key].Id;

                    deptListForArray.push({ 'text': name,
                        'value': id
                    });
                }
                return deptListForArray;
            };


            //绑定部门列表
            function _bindDeptList(deptList) {

                var deptListForArray = _getDeptListForArray(deptList);

                _cmbDeptList
                  .comboxBinding(deptListForArray, 'text', 'value');

                //                if (_selectedDeptId) {
                //                    _cmbDeptList.val(_selectedDeptId);
                //                }
            };


            //将Json格式的该部门的成员列表转换成数组
            function _getMemberListForArray(memberList) {

                var memberListForArray = [];
                for (var key in memberList) {
                    var name = memberList[key].Name;
                    var id = memberList[key].Id;

                    memberListForArray.push({ 'text': name,
                        'value': id
                    });
                }
                return memberListForArray;
            };


            //绑定成员列表
            function _bindMemberList(memberList, userId) {

                var memberDropDownList = _getMemberListForArray(memberList);

                _cmbMemberList
                    .comboxBinding(memberDropDownList, 'text', 'value');

                if (userId) {
                    _cmbMemberList.val(userId);
                }

                options.memberChanged(_cmbMemberList.val());
            };

            //获取当前员工信息
            function _getCurretnUser(options) {
                if (typeof options.currentUser == 'string') {
                    //todo..  
                    return options.currentUser;
                }
                else {
                    return options.currentUser;

                }

            };


            //init memberSelector
            function getInitializeDom(optins) {
                //初始化DOM
                var domRoot = $("<div/>");
                domRoot.append($('<span>部门: </span>'));

                _cmbDeptList =
                    $('<select class="cmbDepartmentList" /><br\>')
                        .css({ 'width': '120px' });
                domRoot.append(_cmbDeptList);

                domRoot.append($('<span>姓名: </span>'));

                _cmbMemberList =
                    $('<select class="cmbMemberList" />')
                        .css({ 'width': '120px' });
                domRoot.append(_cmbMemberList);

                //获取并绑定部门列表
                var deptList = _accessor().getDeptList();
                _bindDeptList(deptList);
                //当前员工
                var currentUser = _getCurretnUser(options);
                $.AjaxBusy.show();
                EzDesk.Service.GetUserInfoInDept_Cache(
                                function (e) {
                                    _bindMemberList(e, currentUser.Id);
                                    $.AjaxBusy.hide();
                                }, { 'deptId': currentUser.Dept.Id });
                _cmbDeptList.val(currentUser.Dept.Id);


                _cmbDeptList.change(function () {
                    $.AjaxBusy.show();
                    EzDesk.Service.GetUserInfoInDept_Cache(
                        function (e) {
                            _bindMemberList(e);
                            $.AjaxBusy.hide();
                        }, { 'deptId': _cmbDeptList.val() }
                    );
                });

                //memberChanged callback
                _cmbMemberList.change(function () {
                    var userId = _cmbMemberList.val();
                    memberChanged(userId);
                });

                return domRoot;
            };

            /* Callback Triggers
            -----------------------------------------------------------------------------*/

            function memberChanged(id) {
                $(_self).trigger('memberChanged', id);
            };






            /* Public Methods
            -----------------------------------------------------------------------------*/

            var publicMethods = {
                'option': function (name, value) {
                    if (value === undefined) {
                        return options[name];
                    }
                    options[name] = value;
                },

                //获得部门信息
                'getDept': function () {
                    var dept = {};
                    dept.Id = _cmbMemberList.val();
                    dept.DeptName = _cmbDeptList.find("option:selected").text();
                    return dept;
                },


                //获得成员信息
                'getMember': function () {
                    var member = {};
                    member.Id = _cmbMemberList.val();
                    member.Name = _cmbMemberList.find("option:selected").text();
                    return member;
                }

                // @other public methods
            };

            $.data(this, ui_name, publicMethods);


            // @private methods


        });

        return this;
    };

    // @static methods

})(jQuery);